const hx = require('hbuilderx')
const viewManager = require('../../utils/view-manager')
const cache = require('../../utils/cache')
const fs = require('fs-extra')
const { join } = require('path')
const { ContinuousLogger } = require('../../utils/log')

function createForm({ title, subtitle, form }) {
    return {
        title: title,
        subtitle: subtitle,
        formItems: [
            {
                type: 'list',
                title: '密钥列表',
                name: 'keys',
                columnStretches: [1],
                items: form.keys,
                value: 0,
                multiSelection: false,
                searchable: false
            },
            {
                type: 'widgetGroup',
                name: 'actions',
                widgets: [
                    {
                        type: 'button',
                        name: 'createKeyPart',
                        text: '创建新的密钥',
                        size: 'small'
                    }
                ]
            }
        ]
    }
}

module.exports = async function (options) {
    const form = {
        keys: []
    }
    async function update() {
        form.keys = []
        const items = await fs.readdir(cache.constant.sshPath)
        items.forEach(it => {
            if (it.endsWith('.pub')) {
                const value = join(cache.constant.sshPath, it)
                form.keys.push({
                    columns: [
                        {
                            label: it.replace('.pub', ''),
                            value
                        }
                    ]
                })
            }
        })
    }
    await update()
    let ui = createForm({
        title: '上传并设置登陆密钥',
        subtitle: '通过上传登陆密钥, 启用安全的 SSH 登录。',
        form
    })
    const data = await hx.window.showFormDialog({
        ...ui,
        width: 490,
        height: 500,
        submitButtonText: '确认',
        cancelButtonText: '取消',
        hideFooterSeparator: true,
        validate: async function () {
            if (form.keys.length == 0) {
                this.showError('没有选择密钥, 请创建密钥')
                return false
            }
            return true
        },
        onChanged: async function (field) {
            if (field == 'actions') {
                await viewManager.open('create-keypair')
                await update()
                let ui = createForm({
                    title: '设置登陆密钥',
                    subtitle: '通过上传登陆密钥到服务器中, 以启用更加安全的 SSH 登录方式。',
                    form
                })
                this.updateForm(ui)
            }
        }
    })
    const client = cache.connections.get(options.host)
    const path = form.keys[data.keys].columns[0].value
    const text = await fs.readFile(path, {
        encoding: 'utf-8'
    })
    const logger = ContinuousLogger.create()
    await client.connection.uploadPublicKeyPair(text, { logger })
    logger.showDetail('设置登录密钥完成, 点击详情查看具体日志。', ['详情'])
}
